<?php
//普通结构无限极
function getTree($array, $pid =0, $level = 0){

    static $list = [];
    foreach ($array as $key => $value){

        if ($value['parent_id'] == $pid){

            $value['level'] = $level;

            $list[] = $value;

            unset($array[$key]);
            getTree($array, $value['id'], $level+1);

        }
    }
    return $list;
}

//树结构无限极
function getTree1($list,$root=0,$child=''){
    $tree=array();
    foreach($list as $key=> $val){
        if($val['parent_id']==$root){
            //获取当前$pid所有子类
            unset($list[$key]);
            if(! empty($list)){
                $child=getTree1($list,$val['id'],$child);

                if(!empty($child)){
                    $val['children']['data']=$child;
                }
            }
            $tree[]=$val;
        }
    }
    return $tree;
}
//修改.env文件 $data数组
function modifyEnv(array $data)
{
    $envPath = base_path() . DIRECTORY_SEPARATOR . '.env';
    $contentArray = collect(file($envPath, FILE_IGNORE_NEW_LINES));
    $contentArray->transform(function ($item) use ($data){
        foreach ($data as $key => $value){

            if(str_contains($item, $key)){

                return $key . '=' . $value;

            }

        }
        return $item;
    });
    $content = implode($contentArray->toArray(), "\n");

    \File::put($envPath, $content);
}

//Ping域名
function ping_time($ip) {
    $ping_cmd = "ping -c 3 -w 5 " . $ip;
    exec($ping_cmd, $info);
    $ping_time_line = end($info);
    try{
    $ping_time = explode("=", $ping_time_line)[1];
    $ping_time_min = explode("/", $ping_time)[0] / 1000.0;
    $ping_time_avg = explode("/", $ping_time)[1] / 1000.0;
    $ping_time_max = explode("/", $ping_time)[2] / 1000.0;

    $result = array();
    $result['ping_min'] = $ping_time_min*1000;
    $result['ping_avg'] = substr($ping_time_avg*1000,0,strpos($ping_time_avg*1000,'.')).'ms';

    $result['ping_max'] = $ping_time_max*1000;

    }catch (Exception $e){
        $result['ping_avg'] ='超时';
    }
    return $result;
}

//隐藏手机号
function hidePhone($str=''){
    $pattern = '/(\d{3})(\d{4})(\d{4})/i';
    $replacement = '$1****$3';
    $resstr = preg_replace($pattern, $replacement,$str);
    return $resstr;
}

//文件下载，返回路径
function voiceUpload($path, $record_sid){
    $dir = "./uploads/voice/" . date("Ym/d", time()).'/';
    $filename = "{$record_sid}.mp3";

    if (!file_exists($dir)){
        mkdir ($dir,0755,true);
    }
    $data = file_get_contents($path);

    file_put_contents($dir.$filename, $data);

    return config('app.url')."{$dir}{$filename}";
}

/**
 * sip文件下载，返回相对路径
 * @param $path  'http://www.tdcall.net/2019-03-03/2019-03-03-16-18-11_928618826581103_172.31.194.139_d001s002.zip'
 * @param $record_sid  文件名称
 * @return string
 */
function voiceUploadA($path, $record_sid){
    $root = env('ROOT_PATH','');
    $dir = "/uploads/voice/" . date("Ym/d", time()).'/';
    $root_dir = $root.$dir;
    $filename = "{$record_sid}";
    \Illuminate\Support\Facades\Log::info('判断路径存不存在',[$root_dir]);
    if (!file_exists($root_dir)){
         mkdir ($dir,0777,true);
        //app('filesystem')->makeDirectory($dir, 0755, true, true);
    }
    $data = file_get_contents($path);

    file_put_contents($root_dir.$filename, $data);

    return "{$dir}{$filename}";
}

//返回本周开始结束时间
function weekTime(){
    $sdefaultDate = date("Y-m-d");
    //$first =1 表示每周星期一为开始日期 0表示每周日为开始日期
    $first=1;
    //获取当前周的第几天 周日是 0 周一到周六是 1 - 6
    $w=date('w',strtotime($sdefaultDate));
    //获取本周开始日期，如果$w是0，则表示周日，减去 6 天
    $week_start=date('Y-m-d',strtotime("$sdefaultDate -".($w ? $w - $first : 6).' days'));
    //本周结束日期
    $week_end=date('Y-m-d',strtotime("$week_start +6 days"));
    return [
        'week_start'=>$week_start.' 00:00:00',
        'week_end' => $week_end.' 23:59:59'
    ];
}
//返回当月第一天和最后一天 month
function getMonth()
{
    $date = date("Y-m-d");
    $firstday = date('Y-m-01', strtotime($date));
    $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day"));
    return [
        'month_start' => $firstday.' 00:00:00',
        'month_end' => $lastday.' 23:59:59'
    ];
}

//给电话+86 $num 手机号
function fullPhone($num){
    if(substr($num,0,3) != '+86'){
        return '+86' . $num;
    }else{
        return $num;
    }
}


//将用户名进行处理，中间用星号表示
function substr_name($user_name)
{
    //获取字符串长度
    $strlen = mb_strlen($user_name, 'utf-8');
    //如果字符创长度小于2，不做任何处理
    if ($strlen < 2) {
        return $user_name;
    } else {
        //mb_substr — 获取字符串的部分
        $firstStr = mb_substr($user_name, 0, 1, 'utf-8');
        $lastStr = mb_substr($user_name, -1, 1, 'utf-8');
        //str_repeat — 重复一个字符串
        return $strlen == 2 ? $firstStr . str_repeat('*',
                mb_strlen($user_name, 'utf-8') - 1) : $firstStr . str_repeat("*", $strlen - 2) . $lastStr;
    }
}

//手机号正则
function checkMobile($str)
{
    $pattern = "/^((13[0-9])|(14[5,7])|(15[0-3,5-9])|(17[0,3,5-8])|(18[0-9])|166|198|199|(147))\d{8}$/";
     if (preg_match($pattern,$str))
     {
         return true;
     }
     else
     {
         return false;
     }
}

//Sip返回录音地址
function sipRecrodUrl($oss_path){
    $arr = explode('/', $oss_path);
    return  $arr[5].'/'.$arr[6];
}

//对sip录音文件地址+1秒的操作
function addSecond($name){
    $name = explode('_', $name);
    $time = $name[0];
    $time_arr = explode('-', $time);
    $time_arr[5] = $time_arr[5]+1;
    $time = implode($time_arr, '-');
    $name[0] = $time;
    $name = implode($name, '_');
    return $name;
}
//对sip录音文件地址-1秒的操作
function SubSecond($name){
    $name = explode('_', $name);
    $time = $name[0];
    $time_arr = explode('-', $time);
    $time_arr[5] = $time_arr[5]-1;
    $time = implode($time_arr, '-');
    $name[0] = $time;
    $name = implode($name, '_');
    return $name;
}